package com.lizk.graph.weight;

import com.lizk.tools.base.Checks;

import java.util.Arrays;

/**
 * @author lizhikui
 * @date 2020/2/15 14:25
 */
public class AdjacencyMatrix implements WeightGraph<Edge<Integer>> {
    /*当前横向迭代的元素索引*/
    int column4Iterator;
    /*当前迭代的元素索引*/
    int row4Iterator;

    /*是否是有向图*/
    boolean directed;

    /*记录节点相连通关系的矩阵*/
    Edge<Integer> [][] g ;

    public AdjacencyMatrix(int n, boolean directed){
        g = new Edge[n][n];
        this.directed = directed;
        for (Edge<Integer>[] edge : g) {
            Arrays.fill(edge, null);
        }
    }


    @Override
    public void iterator(int row){
        this.row4Iterator = row;
        this.column4Iterator = -1;
    }

    @Override
    public boolean hasNext() {
        while ( ++column4Iterator < g.length ){
            if( g[row4Iterator][column4Iterator] != null){
                return true;
            }
        }
        return false;
    }

    @Override
    public Edge<Integer> next() {
        return g[row4Iterator][column4Iterator];
    }


    @Override
    public void addEdge(Edge<Integer> edge) {
        int row = edge.getFrom();
        int col = edge.getTo();
        Checks.checkNotNull(edge);
        if (!hasEdge(edge)){
            g[row][col] = new Edge<>(row,col,edge.getWeight());
            if (!directed){
                g[col][row] = new Edge<>(col,row,edge.getWeight());
            }
        }
    }

    @Override
    public int size() {
        return g.length;
    }

    @Override
    public boolean hasEdge(Edge<Integer> edge) {
        Checks.checkNotNull(edge);
        return g[edge.getFrom()][edge.getTo()] != null;
    }

}





